package com.yuanda.erp9.syn.service.erp9.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.csvreader.CsvReader;
import com.yuanda.erp9.syn.contant.RateCalculateConstants;
import com.yuanda.erp9.syn.entity.CmsBrandsTempEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsInformationEntity;
import com.yuanda.erp9.syn.entity.CmsPricesEntity;
import com.yuanda.erp9.syn.enums.*;
import com.yuanda.erp9.syn.execule.thread.Master;
import com.yuanda.erp9.syn.helper.RetryOperateLogHelper;
import com.yuanda.erp9.syn.poi.Chip1StopCsvData;
import com.yuanda.erp9.syn.pojo.CmsGoodsPojo;
import com.yuanda.erp9.syn.pojo.CmsPricesPojo;
import com.yuanda.erp9.syn.service.erp9.Chip1StopCsvImportService;
import com.yuanda.erp9.syn.service.erp9.SupplierService;
import com.yuanda.erp9.syn.util.*;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zengqinglong
 * @desc chip1Stop数据解析
 * @Date 2022/12/2 14:59
 **/
@Service
@Slf4j
public class Chip1StopCsvImportServiceImpl extends CsvSaveImpl implements Chip1StopCsvImportService {
    @Resource
    private SupplierService supplierService;
    @Autowired
    private RetryOperateLogHelper retryOperateLogHelper;

    // 供应商名称
    private static final String SUPPLIER = "Chip1Stop";

    // 供应商id
    private static final String SUPPLIER_ID = "US000000051";
    protected static CacheUtil.ObjectCache exchangeRates = CacheUtil.objectInit(CachePrefixEnum.EXCHANGE_RATES.getKey());
    private static CacheUtil.Cache brand = CacheUtil.init(CachePrefixEnum.BRAND.getKey());
    private static CacheUtil.Cache suppliers = CacheUtil.init(CachePrefixEnum.SUPPLIERS.getKey());
    private static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

    @Override
    public void analysisChip1Stop(Long topicUpdateLogId, String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return;
        }
        //获取不同Chip1Stop配置文件
        String index = "";
        String hisp = "";
        if (filePath.endsWith("Chip1StopStockList_TI_Arrowtech.csv")) {
            index = "J";
            hisp = "ti";
        } else if (filePath.endsWith("Chip1StopStockList_ver2_Arrowtech.csv")) {
            index = "U";
            hisp = "ver2";
        } else if (filePath.endsWith("Chip1StopStockList_Arrowtech.csv")) {
            index = "O";
            hisp = "other";
        } else {
            return;
        }
        // 处理供应商信息，缓存中没有当前供应商时添加信息到数据库和缓存中
        Integer supplierId = suppliers.get(SUPPLIER);
        if (supplierId == null) {
            // 插入供应商数据
            int insert = supplierService.insertSupplier(SUPPLIER_ID, SUPPLIER);
            supplierId = insert;
        }
        Master<CmsGoodsPojo> objectMaster = new Master<>(supplierId, hisp, SourceEnum.DATA_PACKAGE.getCode());

        // 读取csv数据
        CsvReader csvReader = null;
        try {
            log.info("Chip1Stop数据导入开始");
            csvReader = new CsvReader(filePath, ',');
            // 跳过表头(相当于读取完了表头)
            csvReader.readHeaders();

            long count = 0;
            // 读取每行的内容
            while (csvReader.readRecord()) {
                count++;
                // 获取当前行的所有数据(数组形式)
                String[] values = csvReader.getValues();
                Chip1StopCsvData chip1StopCsvData = Chip1StopCsvData.toChip1StopCsvDataFormat(values);
                if (chip1StopCsvData == null) {
                    continue;
                }
                chip1StopCsvData.setSignIndex(index);
                chip1StopCsvData.setHisp(hisp);
                chip1StopCsvData.setSupplier(supplierId);
                CmsGoodsPojo cmsGoodsPojo = insertDataToDatabase(chip1StopCsvData);
                if (cmsGoodsPojo != null) {
                    objectMaster.add(cmsGoodsPojo);
                }
            }

            if (topicUpdateLogId != null) {
                if (topicUpdateLogId != null) {
                    // 插入系统主体更新数量日志记录表数据
                    cmsTopicUpdateSumLogService.insertOrUpdateByTopicUpdateLogId(count, topicUpdateLogId);
                }
            }

            log.info("Chip1Stop数据导入结束");

        } catch (Exception e) {
            log.warn("解析chip1Stop文件异常:e:", e);
            e.printStackTrace();
        } finally {
            // 退出标志
            objectMaster.isBegin = false;
            map.clear();
            // 读取完成之后,关闭流
            if (csvReader != null) {
                csvReader.close();
            }
        }
    }


    private CmsGoodsPojo insertDataToDatabase(Chip1StopCsvData chip1StopCsvData) {
        try {
            // 包装类
            CmsGoodsPojo cmsGoodsPojo = new CmsGoodsPojo();
            //商品类
            CmsGoodsEntity cmsGoodsEntity = new CmsGoodsEntity();
            cmsGoodsEntity.setAdminid(0);
            cmsGoodsEntity.setTenantsid(0);

            cmsGoodsEntity.setClassifyid(0);
            //img
            cmsGoodsEntity.setImg("");
            cmsGoodsEntity.setType(0);
            cmsGoodsEntity.setStatus(1);
            cmsGoodsEntity.setStatusMsg("");
            cmsGoodsEntity.setDataType(1);
            //产品型号
            if (null == chip1StopCsvData.getManufacturer() || StringUtils.isEmpty(chip1StopCsvData.getManufacturer())) {
                return null;
            }
            String manufacturer = chip1StopCsvData.getManufacturer();

            cmsGoodsEntity.setModel(chip1StopCsvData.getMpn());

            // 处理品牌信息，缓存中没有当前品牌时添加信息到数据库和缓存中
            Integer i = brandCache.get(manufacturer);
            if (i == null) {
                CmsBrandsTempEntity entity = new CmsBrandsTempEntity();
                entity.setName(manufacturer);
                entity.setTag(BrandTagEnum.NEW.getCode());
                CacheUtil.Cache brands = CacheUtil.init(CachePrefixEnum.BRAND.getKey());
                Integer brandId = brands.insertAndGet(entity);
                cmsGoodsEntity.setBrand(brandId);
            } else {
                cmsGoodsEntity.setBrand(i);
            }

            cmsGoodsEntity.setSupplier(chip1StopCsvData.getSupplier());
            cmsGoodsEntity.setIsSampleApply(0);
            //avnet无批次
            cmsGoodsEntity.setBatch("");
            cmsGoodsEntity.setOriginalPrice(new BigDecimal("0.00"));
            cmsGoodsEntity.setPurchasePrice(new BigDecimal("0.00"));
            cmsGoodsEntity.setUnitPrice(0.00);
            //库存
            Integer integer = Integer.valueOf(StringUtils.isEmpty(chip1StopCsvData.getQuantity()) ? "0" : chip1StopCsvData.getQuantity());
            cmsGoodsEntity.setRepertory(integer);
            // 库存所在地
            cmsGoodsEntity.setRepertoryArea("海外");
            cmsGoodsEntity.setPublish(1);
            //描述
            cmsGoodsEntity.setDescribe(chip1StopCsvData.getDescription() == null ? "" : chip1StopCsvData.getDescription().substring(0, chip1StopCsvData.getDescription().length() > 100 ? 100 : chip1StopCsvData.getDescription().length()));
            // files
            cmsGoodsEntity.setFiles("");
            cmsGoodsEntity.setPayType(0);
            //最新起订
            Long minimumOrder = Long.valueOf(StringUtils.isEmpty(chip1StopCsvData.getMoq()) ? "1" : chip1StopCsvData.getMoq());
            cmsGoodsEntity.setMinimumOrder(minimumOrder == 0 ? 1 : minimumOrder);
            if (!StringUtils.isEmpty(chip1StopCsvData.getPriceBreak1())) {
                // mpq
                cmsGoodsEntity.setMpq(Long.valueOf(chip1StopCsvData.getPriceBreak1()));
                //增量
                cmsGoodsEntity.setIncremental(Long.valueOf(chip1StopCsvData.getPriceBreak1()));
            } else {
                // mpq
                cmsGoodsEntity.setMpq(1L);
                //增量
                cmsGoodsEntity.setIncremental(1L);
            }
            // 交货地区
            cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.OTHER.getCode());
            //固定交货日期
            String delivery = "15-25工作日";
            //香港货期算法有变动，是按国内的货期减2天 2023-05-18 赵耀要求更改
            String hkDelivery = "13-23工作日";
            //库存为零期货需要更改为空
            if (integer == 0) {
                //国内交货日期
                cmsGoodsEntity.setDomesticDate("");
                //香港交货时间
                cmsGoodsEntity.setHongkongDate("");
            } else {
                //国内交货日期
                cmsGoodsEntity.setDomesticDate(delivery);
                //香港交货时间
                cmsGoodsEntity.setHongkongDate(hkDelivery);
            }
            //hisp
            cmsGoodsEntity.setHisp(chip1StopCsvData.getHisp());
            cmsGoodsEntity.setSales(0);
            cmsGoodsEntity.setClick(0);
            cmsGoodsEntity.setVisitor(0);
            cmsGoodsEntity.setCreatedAt(DateUtils.now());
            cmsGoodsEntity.setUpdatedAt(DateUtils.now());
            cmsGoodsEntity.setActivityId(0);
            cmsGoodsEntity.setAtlas("");
            // 商品详情
            cmsGoodsEntity.setContent("");
            // eccno
            cmsGoodsEntity.setEccnNo("");

            // 参数
            cmsGoodsEntity.setParams("");
            cmsGoodsEntity.setSource(SourceEnum.DATA_PACKAGE.getCode());
            //供应商名称
            cmsGoodsEntity.setSplName(SUPPLIER);
            //品牌名称
            cmsGoodsEntity.setBrandName(manufacturer);
            cmsGoodsEntity.setCcc(0);
            cmsGoodsEntity.setEmbargo(0);
            // 费率
            JSONObject data = RateCalculateUtil.getRate(cmsGoodsEntity.getBrandName(), cmsGoodsEntity.getModel());

            // 是否需要3c认证
            String ccc = (String) data.get(RateCalculateConstants.CCC_FIELD);
            cmsGoodsEntity.setCcc(Integer.valueOf(ccc));

            // 是否禁运
            String embargo = (String) data.get(RateCalculateConstants.EMBARGO_FIELD);
            cmsGoodsEntity.setEmbargo(Integer.valueOf(embargo));

            //设置eccn
            String eccn = (String) data.get(RateCalculateConstants.ECCN_FIELD);
            cmsGoodsEntity.setEccnNo(eccn);

            // 费率信息
            JSONObject jsonObject = (JSONObject) data.get(RateCalculateConstants.RATE);
            cmsGoodsEntity.setRates(jsonObject);
            if (jsonObject != null && !jsonObject.isEmpty()) {
                // 关税率
                String tariffsRate = jsonObject.getString(RateCalculateConstants.TARIFFRATE_FIELD);
                cmsGoodsEntity.setTariffsRate(Double.valueOf(tariffsRate));

                // 商检费
                String ciqPrice = jsonObject.getString(RateCalculateConstants.CIQPRICE_FIELD);
                cmsGoodsEntity.setInspectionChargesFee(Double.valueOf(ciqPrice));
            }
            //cmsGoodsEntity.setTariffsRate(0);
            //cmsGoodsEntity.setInspectionChargesFee(BigDecimal.ZERO);
            //特殊算法
            String sign = chip1StopCsvData.getSignIndex() + chip1StopCsvData.getSku();
            //sign重复 需要在后面拼接自增
            String signEnd = "";
            if (map.containsKey(sign)) {
                Integer end = map.get(sign) + 1;
                signEnd = "_" + end;
                map.put(sign, end);
            } else {
                map.put(sign, 0);
            }
            String incodes = EasyExcelUtils.getIncodes(sign + signEnd, SUPPLIER_ID, cmsGoodsEntity.getSupplier());
            cmsGoodsEntity.setIncodes(incodes);
            cmsGoodsEntity.setGoodid(incodes);

            // 阶梯价格信息
            cmsGoodsPojo.setCmsPricesEntityList(cmsPrices(chip1StopCsvData, cmsGoodsEntity));
            //商品信息
            cmsGoodsPojo.setCmsGoodsEntity(cmsGoodsEntity);
            // 商品副表信息
            cmsGoodsPojo.setCmsGoodsInformationEntity(cmsGoodsInformation(cmsGoodsEntity));

            return cmsGoodsPojo;
        } catch (Exception e) {
            log.warn("解析异常,放弃当前这条数据,chip1StopCsvData:{}", JSON.toJSON(chip1StopCsvData));
            retryOperateLogHelper.add(chip1StopCsvData, chip1StopCsvData.getSupplier(), e.getMessage());
            return null;
        }
    }

    /**
     * 保存阶梯价格信息
     *
     * @param chip1StopCsvData chip1Stop数据解析
     * @param cmsGoodsEntity   商品信息
     */
    private List<CmsPricesEntity> cmsPrices(Chip1StopCsvData chip1StopCsvData, CmsGoodsEntity cmsGoodsEntity) {
        List<CmsPricesEntity> result = new ArrayList<>();
        Long max = 0L;
        // 一级阶梯价格
        if (!StringUtils.isEmpty(chip1StopCsvData.getPriceUsd1()) && !StringUtils.isEmpty(chip1StopCsvData.getPriceBreak1())) {
            if (Long.valueOf(chip1StopCsvData.getPriceBreak1()) > 0 && Double.valueOf(chip1StopCsvData.getPriceUsd1()) > 0) {
                Long qty = Long.valueOf(chip1StopCsvData.getPriceBreak1());
                //判断当前是不是最后一个阶梯价格
                if (StringUtils.isEmpty(chip1StopCsvData.getPriceBreak2())) {
                    max = 0L;
                } else {
                    max = Long.valueOf(chip1StopCsvData.getPriceBreak2()) - 1;
                }
                result.add(cmsPriceData(qty, max, chip1StopCsvData.getPriceUsd1(), CurrencyEnum.DOLLAR.getCode(), 1, cmsGoodsEntity.getGoodid()));
                //获取第一个阶梯价格
                if (qty == 0) {
                    qty = 1L;
                }
                //设置最小起订量
                if (cmsGoodsEntity.getMinimumOrder() < qty) {
                    cmsGoodsEntity.setMinimumOrder(qty);
                }
               /* //美元需要转成人民币
                Double RMBPrice;
                Object o = exchangeRates.get(CachePrefixEnum.EXCHANGE_RATES.getKey());
                if (o != null) {
                    RMBPrice = (BigDecimal.valueOf(Double.valueOf(chip1StopCsvData.getPriceUsd1())).multiply((BigDecimal) o)).doubleValue();
                } else {
                    RMBPrice = Double.valueOf(chip1StopCsvData.getPriceUsd1());
                }
                //设置单价
                cmsGoodsEntity.setUnitPrice(Double.parseDouble(MathUtil.divide(RMBPrice, qty)));*/
            }
        }

        // 二级阶梯价格
        if (!StringUtils.isEmpty(chip1StopCsvData.getPriceUsd2()) && !StringUtils.isEmpty(chip1StopCsvData.getPriceBreak2())) {
            if (Long.valueOf(chip1StopCsvData.getPriceBreak2()) > 0 && Double.valueOf(chip1StopCsvData.getPriceUsd2()) > 0) {
                Long qty = Long.valueOf(chip1StopCsvData.getPriceBreak2());
                //判断当前是不是最后一个阶梯价格
                if (StringUtils.isEmpty(chip1StopCsvData.getPriceBreak3())) {
                    max = 0L;
                } else {
                    max = Long.valueOf(chip1StopCsvData.getPriceBreak3()) - 1;
                }
                result.add(cmsPriceData(qty, max, chip1StopCsvData.getPriceUsd2(), CurrencyEnum.DOLLAR.getCode(), 2, cmsGoodsEntity.getGoodid()));
            }
        }

        // 三级阶梯价格
        if (!StringUtils.isEmpty(chip1StopCsvData.getPriceUsd3()) && !StringUtils.isEmpty(chip1StopCsvData.getPriceBreak3())) {
            if (Long.valueOf(chip1StopCsvData.getPriceBreak3()) > 0 && Double.valueOf(chip1StopCsvData.getPriceUsd3()) > 0) {
                Long qty = Long.valueOf(chip1StopCsvData.getPriceBreak3());
                //判断当前是不是最后一个阶梯价格
                if (StringUtils.isEmpty(chip1StopCsvData.getPriceBreak4())) {
                    max = 0L;
                } else {
                    max = Long.valueOf(chip1StopCsvData.getPriceBreak4()) - 1;
                }
                result.add(cmsPriceData(qty, max, chip1StopCsvData.getPriceUsd3(), CurrencyEnum.DOLLAR.getCode(), 3, cmsGoodsEntity.getGoodid()));
            }
        }

        // 四级阶梯价格
        if (!StringUtils.isEmpty(chip1StopCsvData.getPriceUsd4()) && !StringUtils.isEmpty(chip1StopCsvData.getPriceBreak4())) {
            if (Long.valueOf(chip1StopCsvData.getPriceBreak4()) > 0 && Double.valueOf(chip1StopCsvData.getPriceUsd4()) > 0) {
                Long qty = Long.valueOf(chip1StopCsvData.getPriceBreak4());
                //判断当前是不是最后一个阶梯价格
                if (StringUtils.isEmpty(chip1StopCsvData.getPriceBreak5())) {
                    max = 0L;
                } else {
                    max = Long.valueOf(chip1StopCsvData.getPriceBreak5()) - 1;
                }
                result.add(cmsPriceData(qty, max, chip1StopCsvData.getPriceUsd4(), CurrencyEnum.DOLLAR.getCode(), 4, cmsGoodsEntity.getGoodid()));
            }
        }

        // 五级阶梯价格
        if (!StringUtils.isEmpty(chip1StopCsvData.getPriceUsd5()) && !StringUtils.isEmpty(chip1StopCsvData.getPriceBreak5())) {
            if (Long.valueOf(chip1StopCsvData.getPriceBreak5()) > 0 && Double.valueOf(chip1StopCsvData.getPriceUsd5()) > 0) {
                Long qty = Long.valueOf(chip1StopCsvData.getPriceBreak5());
                //判断当前是不是最后一个阶梯价格
                if (StringUtils.isEmpty(chip1StopCsvData.getPriceBreak6())) {
                    max = 0L;
                } else {
                    max = Long.valueOf(chip1StopCsvData.getPriceBreak6()) - 1;
                }
                result.add(cmsPriceData(qty, max, chip1StopCsvData.getPriceUsd5(), CurrencyEnum.DOLLAR.getCode(), 5, cmsGoodsEntity.getGoodid()));
            }
        }
        // 六级阶梯价格
        if (!StringUtils.isEmpty(chip1StopCsvData.getPriceUsd6()) && !StringUtils.isEmpty(chip1StopCsvData.getPriceBreak6())) {
            if (Long.valueOf(chip1StopCsvData.getPriceBreak6()) > 0 && Double.valueOf(chip1StopCsvData.getPriceUsd6()) > 0) {
                Long qty = Long.valueOf(chip1StopCsvData.getPriceBreak6());
                result.add(cmsPriceData(qty, 0L, chip1StopCsvData.getPriceUsd6(), CurrencyEnum.DOLLAR.getCode(), 6, cmsGoodsEntity.getGoodid()));
            }
        }


        List<CmsPricesPojo> prices = new ArrayList<>();
        for (CmsPricesEntity cmsPricesEntity : result) {
            CmsPricesPojo cmsPricesPojo = new CmsPricesPojo();
            BeanUtils.copyProperties(cmsPricesEntity, cmsPricesPojo);
            prices.add(cmsPricesPojo);
        }

        // 更新阶梯价格配置到商品表
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(prices, SerializerFeature.WriteMapNullValue));
        cmsGoodsEntity.setPrices(jsonArray.toJSONString());

        return result;
    }


    /**
     * 阶梯价格数据
     *
     * @param min      最小值
     * @param max      最大值
     * @param price    进价
     * @param currency 货币1人民币2美元
     * @param position 位置
     */
    private CmsPricesEntity cmsPriceData(Long min, Long max, String price, Integer currency, Integer position, String goodid) {
        CmsPricesEntity cmsPricesEntity = new CmsPricesEntity();
        cmsPricesEntity.setGoodid(goodid);
        cmsPricesEntity.setLadderid(0);
        cmsPricesEntity.setMin(min);
        cmsPricesEntity.setMax(max == null ? 0L : max);
        if (!Strings.isEmpty(price)) {
            cmsPricesEntity.setPrice(PriceUtil.handlePrice(price));
        } else {
            cmsPricesEntity.setPrice(PriceUtil.handlePrice("0"));
        }
        cmsPricesEntity.setCurrency(currency);
        cmsPricesEntity.setPosition(position);
        cmsPricesEntity.setPublish(1);
        cmsPricesEntity.setCreatedAt(new Date(System.currentTimeMillis()));
        return cmsPricesEntity;
    }

    /**
     * 商品表-副表信息
     *
     * @param cmsGoodsEntity 商品表
     */
    private CmsGoodsInformationEntity cmsGoodsInformation(CmsGoodsEntity cmsGoodsEntity) {
        CmsGoodsInformationEntity cmsGoodsInformationEntity = new CmsGoodsInformationEntity();
        cmsGoodsInformationEntity.setGoodid(cmsGoodsEntity.getGoodid());
        cmsGoodsInformationEntity.setEcnn(1);
        cmsGoodsInformationEntity.setAtlas("");
        cmsGoodsInformationEntity.setContent("");
        cmsGoodsInformationEntity.setActivity(0);
        cmsGoodsInformationEntity.setEcnnnumber(cmsGoodsEntity.getEccnNo());
        cmsGoodsInformationEntity.setTariffs(0);
        cmsGoodsInformationEntity.setTariffsrate(0);
        if (cmsGoodsEntity.getInspectionChargesFee() == null) {
            cmsGoodsInformationEntity.setInspectionCharges(1);
            cmsGoodsInformationEntity.setInspectionChargesFee(0.0);
        } else {
            cmsGoodsInformationEntity.setInspectionCharges(cmsGoodsEntity.getInspectionChargesFee() > 0 ? 1 : 0);
            cmsGoodsInformationEntity.setInspectionChargesFee(cmsGoodsEntity.getInspectionChargesFee());
        }
        cmsGoodsInformationEntity.setParams(cmsGoodsEntity.getParams().toString());
        cmsGoodsInformationEntity.setCreatedAt(new Date());
        return cmsGoodsInformationEntity;
    }
}
